import json, time
from package import view


# 开户装饰器
def outerkaihu(func):
    def inner(*args):
        func(*args)
        # print(111)
        res = time.strftime('%Y-%m-%d %H:%M:%S')
        with open(Control.logurl + Control.name1 + Control.userid1 + '.log', 'a', encoding='utf-8') as file:
            file.write(f'{res}    {Control.name1}开户成功   卡号为{Control.cardid1}\n')

    return inner


# 存钱装饰器
def save(func):
    def inner(*args):
        if func(*args):
            res = time.strftime('%Y-%m-%d %H:%M:%S')
            with open(Control.logurl + Control.name1 + Control.userid1 + '.log', 'a', encoding='utf-8') as file:
                file.write(f'{res}    {Control.name1}存入金额 {Control.money1},余额为{Control.yue1}元\n')

    return inner


# 取钱装饰器
def outerget(func):
    def inner(*args):
        func(*args)
        res = time.strftime('%Y-%m-%d %H:%M:%S')
        with open(Control.logurl + Control.name1 + Control.userid1 + '.log', 'a', encoding='utf-8') as file:
            file.write(f'{res}   {Control.name1}取款{Control.money1},余额为{Control.yue1}\n')

    return inner


# 转账装饰器
def train(func):
    def inner(*args):
        func(*args)
        res = time.strftime('%Y-%m-%d %H:%M:%S')
        with open(Control.logurl + Control.name1 + Control.userid1 + '.log', 'a', encoding='utf-8') as file:
            file.write(f'{res}   {Control.name1}转账给{Control.name2}  RMB {Control.money1}元,余额{Control.yue1}元\n')

    return inner


class Control():

    # 注册用户
    @outerkaihu
    def register(self):
        name = self.__newname()  # 注册名字  return  name
        userid = self.__newuserid()
        password = self.__password()
        phone = self.__phone()
        cardid = self.__cardid()
        self.list1 = [userid, name, cardid, password, 10, False, phone]
        newlist = self.__get_userinfo()
        newlist.append(self.list1)
        with open(self.url, 'w+', encoding='utf-8') as file:
            json.dump(newlist, file)
        print('正在注册')
        time.sleep(1)
        print(f'注册成功,卡号为{cardid}')
        Control.name1 = name
        Control.cardid1 = cardid
        Control.userid1 = userid

    # 查询功能
    def query(self):
        res = self.__confirmcardid()
        if res == 1:
            view.View.showfunction()
            return
        res = self.__confirmpassword()
        if res == True:
            self.__getyue()
            print('正在努力查询,请稍等')
            time.sleep(0.5)
            print(f'账户余额为{self.money}元')

    # 存钱
    @save
    def save_money(self):
        res = self.__confirmcardid()
        if res == 1:
            view.View.showfunction()
            return
        res = self.__confirmpassword()
        while res == True:
            howmuch = input('请输入要存的钱数')
            if howmuch:
                try:
                    howmuch = int(howmuch)
                except:
                    print('输入错误,请重新输入')
                    continue
                if howmuch >= 0:
                    self.__getyue()
                    self.money = self.money + howmuch
                    self.info_list[self.index1][4] = self.money
                    self.__rewrite()
                    print('正在给您数钱,请稍后')
                    time.sleep(1)
                    print('操作成功')
                    Control.name1 = self.username
                    Control.userid1 = self.userid
                    Control.money1 = howmuch
                    Control.yue1 = self.money
                    return  Control.name1,Control.userid1,Control.money1, Control.yue1
                else:
                    print('数额输入错误,请重新输入')
                    return self.save_money()

    # 取钱
    @outerget
    def get_money(self):
        res = self.__confirmcardid()
        if res == 1:
            view.View.showfunction()
            return
        res = self.__confirmpassword()
        while res == True:
            self.howmuch = input('请输入要取的钱数')
            if self.howmuch:
                try:
                    self.howmuch = int(self.howmuch)
                except:
                    continue
                if self.howmuch >= 0:
                    self.__getyue()
                    if self.money >= self.howmuch:
                        self.money = self.money - self.howmuch
                        self.info_list[self.index1][4] = self.money
                        self.__rewrite()
                        print('正在给您数钱')
                        time.sleep(0.5)
                        print('请取走您的现金')
                        Control.name1 = self.username
                        Control.money1 = self.howmuch
                        Control.yue1 = self.money
                        Control.userid1 = self.userid
                        return Control.name1,Control.money1,Control.yue1,Control.userid1
                    else:
                        print('余额不足,请重新输入')
            else:
                print('数额输入错误,请重新输入')

    # 转账
    @train
    def trans_money(self):  # cardid为  self.cardid     self.one为所在的列表
        res = self.__confirmcardid()
        if res == 1:
            view.View.showfunction()
            return
        res = self.__confirmpassword()
        if res == True:
            res1 = self.__confirmzhuan()
            if res1 == True:
                res2 = self.__confirmmoney()  # self.money为转出账户余额
                if res2 == True:
                    print('正在转账,请稍等')
                    time.sleep(1)
                    print('转账成功')
                    Control.name1 = self.username
                    Control.name2 = self.username2
                    Control.userid1 = self.userid
                    Control.money1 = self.zhuanmoney
                    Control.yue1 = self.money - self.zhuanmoney
                    # return Control.name1,Control.name2,Control.userid1,Control.money1,Control.yue1
        self.__zhuanmoney()

    # 更改密码
    def change_pwd(self):
        self.b = 0
        choice = input('1,登陆改密   2,身份验证改密')
        if choice == '1':
            self.__mimagai()
        if choice == '2':
            self.__sfzgai()
        # 更新信息
        if self.b == 1:
            self.__rewrite()
            print('密码修改成功,正在返回')
            time.sleep(0.5)

    # 账户锁定
    def lock(self):
        self.__lock()
        if self.__confirmphone() == True:
            self.__rewrite()
            print('该卡以锁定,正在返回')
            time.sleep(0.5)

    # 账户解锁
    def unlock(self):
        self.__unlock()
        if self.__confirmphone() == True:
            self.__rewrite()
            print('该卡已解锁,正在返回')
            time.sleep(0.5)

    # 补卡
    def new_card(self):
        if self.__new_card() == True:
            if self.__confirmphone() == True:
                print(self.info_list[1][2])
                self.__rewrite()
                print(f'恭喜获得新卡片,卡号为{self.lastnum}')

    # 确认卡号并返回  self.one为所在的列表   self.cardid为登陆的卡号
    # self.info_list 为所有用户信息的列表
    def __confirmcardid(self):
        self.cardid = input('请输入卡号')
        self.info_list = self.__get_userinfo()
        a = 1
        for i in self.info_list:
            if i[2] == self.cardid:
                self.one = i
                if self.isfrozen() == True:
                    print('该账户已冻结,请更换账户')
                    return 1
                a = 0
                self.count = 1
                self.username = i[1]
                self.userid = i[0]
                return self.cardid,self.count,self.username,self.userid
        if a == 1:
            print('卡号错误,请重新输入')
            return self.__confirmcardid()

    # 确认密码  如果正确返回True   或冻结    self.info_list[self.index1][3]为正确的密码
    def __confirmpassword(self):
        self.password = input('请输入密码')
        self.index1 = self.info_list.index(self.one)  # 获取卡号对应的密码
        if self.info_list[self.index1][3] == self.password:  # 如果输入的密码正确

            return True
        elif self.count == 3:
            return self.__frozencard()
        else:
            print('密码错误,请重新输入')
            self.count += 1
            return self.__confirmpassword()

    def __frozencard(self):  # 密码错误次数过多,冻结账户
        print('密码错误次数过多,账户已冻结')
        self.info_list[self.index1][5] = True
        with open(self.url, 'w+', encoding='utf-8') as file:
            json.dump(self.info_list, file)
        return

    # 密码正确后,根据账号获取余额   返回self.money
    def __getyue(self):
        self.money = self.info_list[self.index1][4]  # 获取卡里的余额

    # self.one  为要转至的列表
    def __confirmzhuan(self):
        self.cardid_1 = input('请输入要转账的卡号')
        a = 1
        b = -1
        for i in self.info_list:
            b += 1
            if i[2] == self.cardid_1:
                a = 0
                self.one = self.info_list[b]
                self.username2 = self.one[1]
                return True
        if a == 1:
            print('卡号错误或不存在,请重新输入')
            return self.__confirmzhuan()

    # 确认余额是否足够
    def __confirmmoney(self):
        self.__getyue()
        self.zhuanmoney = input('请输入转账金额')
        try:
            self.zhuanmoney = float(self.zhuanmoney)
        except:
            print('金额输入错误,请重新输入')
            return self.__confirmmoney()
        if self.zhuanmoney <= self.money:
            return True
        else:
            print('金额输入有误,请重新输入')
            self.__confirmmoney()

    # 重写用户列表信息
    def __rewrite(self):
        with open(self.url, 'w+', encoding='utf-8') as file:
            json.dump(self.info_list, file)

    # self.info_list[self.index1]  为登陆用户所在的列表
    def __zhuanmoney(self):
        # 修改转账者的信息
        self.info_list[self.index1][4] = self.money - self.zhuanmoney
        # 获取收款者的信息
        index2 = self.info_list.index(self.one)
        # 修改收款者的信息
        self.info_list[index2][4] = self.info_list[index2][4] + self.zhuanmoney
        with open(self.url, 'w+', encoding='utf-8') as file:
            json.dump(self.info_list, file)

    # 通过登录改密
    def __mimagai(self):
        res = self.__confirmcardid()
        if res == True:
            view.View.showfunction()
        res = self.__confirmpassword()
        while res == True:
            mima = input('请输入新密码')
            remima = input('请确认密码')
            if mima == remima:
                self.info_list[self.index1][3] = mima
                self.b = 1
                break
            else:
                print('密码错误,请重新输入')

    # 通过身份证改密
    def __sfzgai(self):
        self.__get_userinfo()
        sfid = input('请输入身份证号码')
        a = 1
        for i in self.info_list:
            if i[0] == sfid:
                self.one = i
                if self.__confirmphone() == True:
                    while True:
                        a = 0
                        newpassword = input('请输入新密码')
                        renewpassword = input('请确认密码')
                        if newpassword == renewpassword:
                            i[3] = newpassword
                            self.b = 1
                            self.one = i
                            break
                        else:
                            print('两次密码不一致,请重新输入')
        if a == 1:
            print('未找到身份信息,请重新输入')
            return self.__sfzgai()

    # 通过身份证号锁定
    def __lock(self):
        self.__get_userinfo()
        self.userid = input('请输入身份证号码')
        a = 1
        for i in self.info_list:
            if i[0] == self.userid:
                a = 0
                self.one = i
                i[5] = True
        if a == 1:
            print('未搜索到该身份信息,请确认后重新输入')
            return self.__lock()

    # 通过身份证号解锁
    def __unlock(self):
        self.__get_userinfo()
        self.userid = input('请输入身份证号码')
        a = 1
        for i in self.info_list:
            if i[0] == self.userid:
                a = 0
                i[5] = False
                self.one = i
        if a == 1:
            print('未搜索到该身份信息,请确认后重新输入')
            return self.__unlock()

    #补卡
    def __new_card(self):
        self.__get_userinfo()
        sfid = input('请输入身份证号码')
        a = 1
        for i in self.info_list:
            if i[0] == sfid:
                a = 0
                self.lastnum = int(self.info_list[-1][2]) + 1
                i[2] = str(self.lastnum)
                self.one = i
                return True
        if a == 1:
            print('未检测到该身份信息,请确认后重新输入')
            return self.__new_card()

    # 确认身份证号对应的手机号
    def __confirmphone(self):
        self.phonenum = input('请输入绑定的手机号')
        if self.one[6] == self.phonenum:
            return True
        else:
            print('手机号有误,请重新输入')
            print('若手机号已更改,请去人工柜台办理变更')
            return self.__confirmphone()

    # 获取用户信息列表           返回self.info_list  所有用户信息
    url = './database/userdata.json'

    def __get_userinfo(self):
        with open(self.url, 'a+', encoding='utf-8') as file:
            file.seek(0)
            self.info_list = json.load(file)
            return self.info_list

    # 注册名字
    def __newname(self):
        self.name = input('请输入用户名')
        if not self.name:
            print('用户名错误,请重新输入')
            return self.__newname()
        else:
            return self.name

    # 注册身份证              return  self.userid
    def __newuserid(self):
        self.__get_userinfo()
        a = 1
        self.userid = input('请输入身份证号')
        if len(self.userid)==3:
            for i in self.info_list:
                if i[0] == self.userid:
                    a = 0
                    print('该身份证号已拥有本行银行卡,请更换身份证')
                    self.__newuserid()
            if a == 1:
                return self.userid
        else:
            print('身份证号错误,请重新输入')
            return self.__newuserid()

    # 密码及确认密码     return self.password
    def __password(self):
        self.password = input('请设置密码(6位数字)')
        if len(self.password) == 6 and self.password.isdigit():
            self.repassword = input('请确认密码')
            if self.password == self.repassword:
                return self.password
            else:
                print('两次输入的密码不一致,请重新设置')
                self.__password()
        else:
            print('密码格式错误,请重新设置')
            self.__password()

    # 收集手机号              return self.phone
    def __phone(self):
        self.phone = input('请输入手机号')
        if len(self.phone) == 11 and self.phone.isdigit():
            return self.phone
        else:
            print('手机号格式错误,请重新输入')
            self.__phone()

    # 创建卡号         return  newcardid
    def __cardid(self):
        n=1
        while True:
            a = 1
            self.__get_userinfo()
            self.newcardid = int(self.__get_userinfo()[-1][2]) + n
            for i in self.info_list:
                if self.newcardid==int(i[2]):
                    n+=1
                    a=0
            if a==1:
                return str(self.newcardid)

    def isfrozen(self):
        if self.one[5] == True:
            return True
        return False


Control.logurl = './log/'
Control.name1 = None
Control.name2 = None
Control.money1 = None
Control.yue1 = None
Control.cardid1 = None
Control.userid1 = None

if __name__ == '__main__':
    quit()
